package jmine.tec.database.query.columns;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import bancosys.tec.utils.date.Timestamp;

/**
 * Coluna de data
 * 
 * @author lundberg
 */
public class TimestampColumn extends AbstractColumn {

    private static final String PATTERN = "dd/MM/yyyy HH:mm:ss";

    /**
     * Construtor
     * 
     * @param type type
     * @param name name
     */
    public TimestampColumn(int type, String name) {
        super(type, name);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String read(ResultSet rs) {
        try {
            java.sql.Timestamp value = rs.getTimestamp(this.getName());
            if (value == null) {
                return "null";
            } else {
                return new SimpleDateFormat(PATTERN).format(value);
            }
        } catch (SQLException e) {
            return super.read(rs);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void setParameter(PreparedStatement st, int parameterIndex, String value) throws SQLException {
        try {
            java.sql.Timestamp parameter = new java.sql.Timestamp(new Timestamp(new SimpleDateFormat(PATTERN).parse(value)).getTime());
            st.setTimestamp(parameterIndex, parameter);
        } catch (ParseException e) {
            throw new IllegalArgumentException("Valor deve ser uma data no formato dd/MM/yyyy: " + value, e);
        }
    }
}
